package com.example.annotation.datasource;

import java.util.Map;

import javax.sql.DataSource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import com.example.annotation.contextholders.DynamicDataSourceContextHolder;

import lombok.extern.slf4j.Slf4j;

/**
 * @author fz
 * @creation time 2021/5/20
 */
@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {


    public DynamicDataSource(DataSource defaultDataSource, Map<Object, Object> targetDataSources) {
        log.info("===============DynamicDataSource加载数据源=================");
        //配置默认的数据源
        super.setDefaultTargetDataSource(defaultDataSource);
        //配置目标数据源
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        log.info("===================determineCurrentLookupKey切换数据源=========================");
        return DynamicDataSourceContextHolder.getDataSourceType();
    }
}
